// 新增/编辑实物库存
<template>
  <div class="inventory-update layout-content">
    <a-spin :spinning="loading">
      <c-form
        v-model="form"
        :data="formData"
        ref="form"
        :rules="formRules"
        layout="inline"
        :col="{ labelCol: { style: 'width:80px' } }"
      >
        <template v-slot:category>
          <span v-if="isUpdate">{{ inventoryDetail.categoryName }}</span>
          <c-category
            v-model="form.category"
            style="width: 184px;"
            v-else
          ></c-category>
        </template>
        <template v-slot:warehouseId>
          <span v-if="isUpdate">{{
            inventoryDetail.warehouse && inventoryDetail.warehouse.shortName
          }}</span>
          <a-select
            v-model="form.warehouseId"
            optionFilterProp="children"
            show-search
            style="width: 184px;margin-right: 16px;"
            placeholder="请选择仓库"
            v-else
          >
            <template v-for="item in allWarehouses">
              <a-select-option :value="item.id" :key="item.id"
                >{{ item.shortName }}
              </a-select-option>
            </template>
          </a-select>
          <span v-if="!isUpdate">
            <span>找不到仓库?</span>
            <c-button type="link" @click="addWarehouse">新增仓库</c-button>
          </span>
        </template>
      </c-form>
      <a-divider />
      <p>实物库存明细录入：</p>
      <c-table
        :data="tableData"
        :columns="columns"
        :rowClassName="
          () => {
            return 'inputRow';
          }
        "
        :showHeader="false"
        size="small"
      >
        <template v-for="item in slots" v-slot:[item.dataIndex]="row">
          <a-input
            :key="item.dataIndex"
            v-model="row.value[item.dataIndex]"
            :placeholder="`请输入${item.title}`"
          ></a-input>
        </template>
        <template v-slot:handle="{ idx }">
          <div class="handle">
            <a-icon
              type="plus"
              v-if="idx === 0"
              class="primary fontw"
              @click="addRow"
            ></a-icon>
            <a-icon
              type="minus"
              v-else
              class="danger fontw"
              @click="delRow(idx)"
            ></a-icon>
          </div>
        </template>
      </c-table>
      <div class="excel info" style="margin-top:6px;" v-if="!isUpdate">
        输入太麻烦？Excel批量导入！ 请先
        <Download
          name="实物库存明细"
          :titles="downloadTitles"
          :data="downloadData"
        />
        ，然后按照模板格式填写，之后点击
        <ImportExcel :titles="downloadTitles" @change="importExcel" />
      </div>
      <div class="tips">
        <a-icon type="exclamation-circle" class="primary" />
        <div class="tip desc">
          <ul>
            <li>
              <p>
                1.品牌、规格、材料号/捆包号和实物重量必填，其他选填，其中材料号/捆包号在统一企业下不能有重复的数值
              </p>
            </li>
            <li>
              <p>
                2.此处为实物库存录入，请务必填写真实的实物重量，生成合同时，客户可选择对应的实物，然后结算具体合同金额
              </p>
            </li>
            <li>
              <p>
                3.请务必检查选择的品种、品牌、规格、材质等是否正确，若存在错误的，系统无法自动匹配对应商城订单的商品，导致客户无法挑选实物
              </p>
            </li>
            <li>
              <p>
                4.商品对应的仓库请认真核对，如果存在同一个仓库有多个不同简称的，请务必在仓库管理中将这些仓库关联起来，否则库存将无法统计
              </p>
            </li>
            <li>
              <p>5.库存明细里面的备注为选填，填了之后，客户挑选时可见</p>
            </li>
          </ul>
        </div>
      </div>
      <c-button type="primary" @click="submit">确认录入</c-button>
    </a-spin>
    <UpdateWarehouse
      v-model="addWarehouseVisible"
      title="新增仓库"
      @updated="updatedWarehouse"
    />
  </div>
</template>

<script>
import { getcompanywarehouses } from "@/api/warehouse";
import {
  addentityinventory,
  getentityinventorybyid,
  updateentityinventory
} from "@/api/inventory";
import Download from "@/components/download-excel";
import ImportExcel from "@/components/lead-in-excel";
import { uniq } from "lodash";
import UpdateWarehouse from "@/views/warehouse/list/components/update";

export default {
  components: {
    Download,
    ImportExcel,
    UpdateWarehouse
  },
  data() {
    return {
      loading: false,
      inventoryDetail: {},
      allWarehouses: [],
      form: {
        category: [],
        warehouseId: undefined
      },
      formData: [
        {
          label: "商品品种",
          prop: "category",
          slot: "category"
        },
        {
          label: "所属仓库",
          prop: "warehouseId",
          slot: "warehouseId"
        }
      ],
      formRules: {
        category: [
          { required: true, message: "请选择商品品种", trigger: "change" }
        ],
        warehouseId: [
          { required: true, message: "请选择仓库", trigger: "change" }
        ]
      },
      tableData: [
        {
          brand: undefined,
          spec: undefined,
          material: undefined,
          other: undefined,
          positionCode: undefined,
          materialCode: undefined,
          weight: undefined,
          remark: undefined,
          purchasePrice: undefined
          // totalPurchasePrice: undefined
        }
      ],
      columns: [
        {
          title: "品牌",
          dataIndex: "brand",
          scopedSlots: { customRender: "brand" }
        },
        {
          title: "规格",
          dataIndex: "spec",
          scopedSlots: { customRender: "spec" }
        },
        {
          title: "材质",
          dataIndex: "material",
          scopedSlots: { customRender: "material" }
        },
        {
          title: "其他",
          dataIndex: "other",
          scopedSlots: { customRender: "other" }
        },
        {
          title: "库位号",
          dataIndex: "positionCode",
          scopedSlots: { customRender: "positionCode" }
        },
        {
          title: "材料号/捆包号",
          dataIndex: "materialCode",
          scopedSlots: { customRender: "materialCode" }
        },
        {
          title: "实物重量",
          dataIndex: "weight",
          scopedSlots: { customRender: "weight" }
        },
        {
          title: "备注",
          dataIndex: "remark",
          scopedSlots: { customRender: "remark" }
        },
        {
          title: "成本价（采购单价）",
          dataIndex: "purchasePrice",
          scopedSlots: { customRender: "purchasePrice" }
        },
        // {
        //   title: "成本金额（采购总金额）",
        //   dataIndex: "totalPurchasePrice",
        //   scopedSlots: { customRender: "totalPurchasePrice" }
        // },
        {
          title: "操作",
          dataIndex: "handle",
          scopedSlots: { customRender: "handle" },
          hidden: this.$route.name === "inventoryUpdate"
        }
      ],
      addWarehouseVisible: false // 新增仓库弹窗
    };
  },
  computed: {
    // 是否编辑
    isUpdate() {
      return this.$route.name === "inventoryUpdate";
    },
    // 表格插槽，剔除操作列
    slots() {
      let columns = this.columns.filter(i => i.dataIndex !== "handle");
      return columns;
    },
    // 模板表头
    downloadTitles() {
      let res = {};
      let cols = this.columns.filter(i => i.dataIndex !== "handle");
      for (let i = 0; i < cols.length; i++) {
        res[cols[i].title] = cols[i].dataIndex;
      }
      return res;
    },
    // 模板数据
    downloadData() {
      return [
        {
          brand: undefined,
          spec: undefined,
          material: undefined,
          other: undefined,
          positionCode: undefined,
          materialCode: undefined,
          weight: undefined,
          remark: undefined,
          purchasePrice: undefined
          // totalPurchasePrice: undefined
        }
      ];
    }
  },
  methods: {
    // 新增仓库回调
    updatedWarehouse() {
      this.addWarehouseVisible = false;
      this.getAllWarehouse();
    },
    // 导入excel
    importExcel(data) {
      this.tableData = data;
    },
    // 前往仓库管理
    addWarehouse() {
      this.addWarehouseVisible = true;
    },
    // 新增一行
    addRow() {
      let row = Object.assign({}, this.tableData[0]);
      this.tableData.push(row);
    },
    // 删除一行
    delRow(idx) {
      this.tableData.splice(idx, 1);
    },
    getAllWarehouse() {
      getcompanywarehouses().then(res => {
        this.allWarehouses = res;
      });
    },
    // 校验
    validate() {
      return new Promise(resolve => {
        this.$refs.form.validated().then(() => {
          let len = this.tableData.length;
          let brands = this.tableData.filter(i => i.brand);
          let specs = this.tableData.filter(i => i.spec);
          let materialCodes = this.tableData.filter(i => i.materialCode);
          let weights = this.tableData.filter(i => i.weight);
          if (
            brands.length === len &&
            specs.length === len &&
            materialCodes.length === len &&
            weights.length === len
          ) {
            // 检查有无重复材料号
            let materials = uniq(materialCodes.map(i => i.materialCode));
            if (materials.length === this.tableData.length) {
              resolve();
            } else {
              this.$message.warning("材料号/捆包号不能重复");
            }
          } else {
            let msg = `请补全${brands.length === len ? "" : "品牌"}${
              brands.length !== len &&
              (specs.length !== len ||
                materialCodes.length !== len ||
                weights.length !== len)
                ? "、"
                : ""
            }${specs.length === len ? "" : "规格"}${
              specs.length !== len &&
              (materialCodes.length !== len || weights.length !== len)
                ? "、"
                : ""
            }${materialCodes.length === len ? "" : "材料号/捆包号"}${
              materialCodes.length !== len && weights.length !== len ? "、" : ""
            }${weights.length === len ? "" : "实物重量"}`;
            this.$message.warning(msg);
          }
        });
      });
    },
    submit() {
      this.validate().then(() => {
        this.loading = true;
        // 新增、编辑调用不同接口
        if (this.isUpdate) {
          let params = {
            ...this.tableData[0],
            entityInventoryId: this.inventoryDetail.id,
            version: this.inventoryDetail.version
          };
          updateentityinventory(params)
            .then(() => {
              this.$message.success("操作成功");
              this.$router.push({ name: "inventory" });
            })
            .finally(() => {
              this.loading = false;
            });
        } else {
          addentityinventory({
            categoryId: this.form.category[1],
            warehouseId: this.form.warehouseId,
            entityInventoryDetailList: this.tableData
          })
            .then(() => {
              this.$message.success("操作成功");
              this.$router.push({ name: "inventory" });
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
    init() {
      if (this.isUpdate) {
        let query = this.$route.query;
        getentityinventorybyid({
          entityInventoryId: query.id,
          version: query.version
        }).then(res => {
          this.inventoryDetail = res;
          this.form.category = res.categoryId;
          this.form.warehouseId = res.warehouse.id;
          for (const key in this.tableData[0]) {
            this.tableData[0][key] = res[key];
          }
        });
      }
    }
  },
  created() {
    this.init();
    this.getAllWarehouse();
  }
};
</script>

<style lang="scss" scoped>
.inventory-update ::v-deep .c-table {
  .inputRow td {
    padding-top: 0 !important;
    padding-bottom: 0 !important;
  }
  .ant-input {
    border: 0;
    padding: 0;
    width: 100% !important;
  }
  .ant-input:focus {
    box-shadow: none !important;
  }
}
.excel ::v-deep .ant-btn-link {
  padding: 0;
}
.tips {
  margin: 24px 0;
  .tip {
    display: inline-grid;
    margin-left: 10px;
  }
}
</style>
